﻿using Microsoft.AspNetCore.Http;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Service.Core.Swagger.Filters;


public class FileUploadOperation : IOperationFilter
{
    //public void Apply(OpenApiOperation operation, OperationFilterContext context)
    //{
    //    //判断上传文件的类型，只有上传的类型是IFormCollection的才进行重写。
    //    if (context.ApiDescription.ActionDescriptor.Parameters.Any(w => w.ParameterType == typeof(IFormFile)))
    //    {
    //        var parameters = context.ApiDescription.ActionDescriptor.Parameters;
    //        Dictionary<string, OpenApiSchema> schema = new Dictionary<string, OpenApiSchema>();
    //        schema[parameters[0].Name] = new OpenApiSchema
    //        {
    //            Description = "请选择文件",
    //            Type = "string",
    //            Format = "binary"
    //        };
    //        Dictionary<string, OpenApiMediaType> content = new Dictionary<string, OpenApiMediaType>();
    //        content["multipart/form-data"] = new OpenApiMediaType
    //        {
    //            Schema = new OpenApiSchema { Type = "object", Properties = schema }
    //        };
    //        operation.RequestBody = new OpenApiRequestBody() { Content = content };
    //    }
    //}




    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        // 检查是否包含 IFormFile 类型的参数
        var fileParameters = context.ApiDescription.ActionDescriptor.Parameters
            .Where(p => p.ParameterType == typeof(IFormFile))
            .ToList();

        if (fileParameters.Any())
        {
            // 创建一个字典来存储文件参数的 Schema
            var schema = new Dictionary<string, OpenApiSchema>();

            foreach (var param in fileParameters)
            {
                schema[param.Name] = new OpenApiSchema
                {
                    Description = $"请选择文件 ({param.Name})",
                    Type = "string",
                    Format = "binary"
                };
            }

            // 创建一个 OpenApiMediaType 对象
            var mediaType = new OpenApiMediaType
            {
                Schema = new OpenApiSchema
                {
                    Type = "object",
                    Properties = schema
                }
            };

            // 创建请求体的内容
            var requestBodyContent = new Dictionary<string, OpenApiMediaType>
        {
            { "multipart/form-data", mediaType }
        };

            // 设置请求体
            operation.RequestBody = new OpenApiRequestBody
            {
                Content = requestBodyContent,
                Required = true // 根据需求设置是否必填
            };
        }
    }
}
